import 'package:get/get.dart';
import '../../../service/HttpsClient.dart'; // 导入自定义的HttpsClient类
import '../../../models/pcate_model.dart';
import '../../../models/selected_cate_model.dart';

class CategoryController extends GetxController {
  //TODO: Implement CategoryController
  RxInt selectIndex = 0.obs;
  RxList<PcateItemModel> menuList = <PcateItemModel>[].obs;
  RxList<SelectedCateItemModel> selectedList = <SelectedCateItemModel>[].obs;
  HttpsClient httpsClient = HttpsClient();

  // 点击菜单栏事件
  void changeIndex(int index, String pid) {
    selectIndex.value = index;
    getSelectedCateData(pid);
  }

  // 获取左边一级分类列表
  void getMenuData() async {
    var response = await httpsClient.get("api/pcate");
    if (response != null) {
      PcateModel pcateModel = PcateModel.fromJson(response);
      menuList.value = pcateModel.result!;
      // 默认获取第一个菜单栏的商品列表
      getSelectedCateData(menuList[0].sId!);
    }
  }

  // 点击指定菜单获取右边商品
  void getSelectedCateData(String id) async {
    var response = await httpsClient.get("api/pcate?pid=$id");
    if (response != null) {
      SelectedCateModel selectedCateModel = SelectedCateModel.fromJson(response);
      selectedList.value = selectedCateModel.result!;
      update();
    }
  }

  @override
  void onInit() {
    super.onInit();
    getMenuData(); // 获取菜单数据
  }

  @override
  void onClose() {
    super.onClose();
  }
}
